import {reqCartList, reqDeleteCart, reqUpdateCheckedById} from "network/home";

const state = {
  cartList: []
};

const mutations = {
  GETCARTLIST(state, cartList) {
    state.cartList = cartList
  }
};

const actions = {
  //获取购物车列表
  async getCartList(context) {
    let result = await reqCartList()
    // console.log(result)
    if (result.code === 200) {
      context.commit('GETCARTLIST', result.data)
    }
  },
  //删除购物车产品
  async deleteCartListBySkuId(content, skuId) {
    let result = await reqDeleteCart(skuId)
    if (result.code === 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  //修改购物车产品选中状态
  async updateCheckedById(context, {skuId, isChecked}) {
    let result = await reqUpdateCheckedById(skuId, isChecked)
    if (result.code === 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  //删除全部勾选的产品
  deleteAllCheckedCart(context) {
    //获取购物车中全部的产品
    let result = context.getters.cartList.cartInfoList
    let PromiseAll = []
    result.forEach(item => {
      let promise = item.isChecked === 1 ? context.dispatch('deleteCartListBySkuId', item.skuId) : '';
      //将每一次返回的promise添加到数组中
      PromiseAll.push(promise)
    })
    //只要全部的 p1 | p2... 都成功 返回的结果即为成功
    // 如果有一个失败， 返回结果即为失败
    return Promise.all(PromiseAll)
  },
  //修改产品选中状态
  updateAllCartIsChecked({dispatch, state}, isChecked) {
    let promiseAll = []
    state.cartList[0].cartInfoList.forEach(item => {
      let promise = dispatch('updateCheckedById', {skuId: item.skuId, isChecked})
      promiseAll.push(promise)
    })
    //最终返回的结果
    return Promise.all(promiseAll)
  }
};

const getters = {
  cartList(state) {
    return state.cartList[0] || {}
  },

};

export default {
  state,
  actions,
  mutations,
  getters
}